package com.sayimo.maker.mall.goods.service.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sayimo.framework.exception.DaoException;
import com.sayimo.framework.exception.ServiceException;
import com.sayimo.maker.commons.Constant;
import com.sayimo.maker.commons.utils.RedisUtils;
import com.sayimo.maker.commons.utils.SearchUtil;
import com.sayimo.maker.mall.goods.dao.GoodsClassInterfaceDao;
import com.sayimo.maker.mall.goods.dao.GoodsListInterfaceDao;
import com.sayimo.maker.mall.goods.service.GoodsClassInterfaceService;
import com.sayimo.maker.mall.search.vo.SearchField;

/**
 * @Copyright (c) 2016 广东省尚一互联网有限公司
 * @Project: maker-mall
 * @ClassName: GoodsClassInterfaceImplService.java
 * @Description: 商品分类Service
 * @Author:	tanxin
 * @Date:2017年2月13日,下午5:45:58
 * @Version 1.0.0
 */
@Service(value = "goodsClassInterfaceImplService")
public class GoodsClassInterfaceImplService implements GoodsClassInterfaceService {

	private static Log logger = LogFactory.getLog(GoodsClassInterfaceImplService.class);
	@Autowired
	private GoodsClassInterfaceDao goodsClassInterfaceDao;
	@Autowired
	private GoodsListInterfaceDao goodsListInterfaceDao;

	@Autowired
	private HttpServletRequest request;

	public GoodsClassInterfaceDao getGoodsClassInterfaceDao() {
		return goodsClassInterfaceDao;
	}

	public void setGoodsClassInterfaceDao(GoodsClassInterfaceDao goodsClassInterfaceDao) {
		this.goodsClassInterfaceDao = goodsClassInterfaceDao;
	}

	/**
	 * 
	 * @Title: goodsClassList @Description: 商品分类列表 @return @throws
	 * ServiceException @return Map<String,Object> @throws
	 */
	@Override
	public Map<String, Object> goodsClassList() throws ServiceException {

		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
		List list = new ArrayList();
		Map<String, List> dataMap = new HashMap();
		String _classId = request.getParameter("classId");
		String _providerId = request.getParameter("providerId");
		String mallType = request.getParameter("mallType");
		logger.info("classId = " + _classId);
		Integer classId = 0, providerId = null;
		
		if (StringUtils.isNotEmpty(_classId)) {
			classId = Integer.parseInt(_classId);
		}
		String key = RedisUtils.GOODSCLASS_CACHE +mallType+ "_"+classId;
		
		// 获取供应商下的分类信息
		if (StringUtils.isNotEmpty(_providerId)) {
			providerId = Integer.parseInt(_providerId);
			key = RedisUtils.PROVIDER_CLASSIDS_CACHE + _providerId;
		}
		
		
		if (RedisUtils.hasKey(key)) {
			logger.info("get data from cache..., key = " + key);
			list = RedisUtils.getListCache(key, null, null, Map.class);
			dataMap.put("goodsclasslist", list);
			logger.info("list = " + list);
			resultMap.put(Constant.DATA, dataMap);
			return resultMap;
		}

		try {
			if (StringUtils.isNotEmpty(_providerId)) {
				Map paramMap = new HashMap();
				paramMap.put("providerId", providerId);
				Map providerGoodsClassIdMap = goodsClassInterfaceDao.getGoodsClassIdsPolyProviderId(paramMap);
				if (providerGoodsClassIdMap == null) {
					resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
					resultMap.put(Constant.DATA, list);
					return resultMap;
				}
				
				String goodsClassIds = providerGoodsClassIdMap.get("goodsClassIds")==null?null:providerGoodsClassIdMap.get("goodsClassIds").toString();
				if(goodsClassIds!=null){
					String classIds = getClassIds(goodsClassIds);

					String[] classIdsArr = classIds.split(",");
					Integer[] classIdsArrInteger=new Integer[classIdsArr.length];
					for(int i=0 ; i <classIdsArr.length ; i++){
						classIdsArrInteger[i]=Integer.parseInt(classIdsArr[i]);
						List providerClass=goodsClassInterfaceDao.getGoodsClassesById(classIdsArrInteger[i]);
						list.addAll(providerClass);
					}
				}
				
				dataMap.put("goodsclasslist", list);
				resultMap.put(Constant.DATA, dataMap);
				return resultMap;
					
			}
			
			list = goodsClassInterfaceDao.getGoodsClassesByPid(classId);
			dataMap.put("goodsclasslist", list);

			
			resultMap.put(Constant.DATA, dataMap);
			return resultMap;
		} catch (DaoException e) {
			logger.error(e);
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR);
			return resultMap;
		}

	}

	/**
	 * @Title: queryGoodsListByClassId
	 * @Description: 根据分类ID查询商品列表
	 * @throws ServiceException
	 * @return Map<String,Object>
	 * @param classId
	 * @param goodsName
	 */
	@Override
	public Map<String, Object> queryGoodsListByClassId(Integer mallType ,Integer classId ,Integer pageSize,Integer pageNow,
			String goodsName,Integer sortWord,Integer sortMode,Integer brandId,String isStudent,
			Integer providerId,String timestamp) throws ServiceException {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			//查询商品最新修改的时间
			Map dataMap=goodsListInterfaceDao.updateTimeComparison();
			Date date = (Date) dataMap.get("time");
			String times = Long.toString(date.getTime());
			
//			String _isStudent = request.getParameter("isStudent");
			//对比时间戳
			if(times.equals(timestamp)){
				map.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				map.put(Constant.DATA, null);
				return map;
			}
			
			SolrServer solrServer = SearchUtil.getSolrServer();
			SolrQuery solrQuery = new SolrQuery();
			logger.info("goodsName = " + goodsName);
			
			Pattern pattern = Pattern.compile(Constant.REGEX_NUM_LATTER);
			Matcher matcher = null;
			StringBuilder builder = new StringBuilder();
			if (StringUtils.isNotEmpty(goodsName)) {
				goodsName = URLDecoder.decode(goodsName, "UTF-8");
				matcher = pattern.matcher(goodsName);
				if (matcher.find()) {
					builder.append(matcher.group().toLowerCase());
				}
				logger.info("build = " + builder.toString());
			}
			solrQuery.set("q", "pinyin:" + (StringUtils.isEmpty(builder.toString()) ? "*" : builder.toString()))
				.set("fq", "type:COMMONS")
				.set("defType", "edismax")
				.set("mm", 20);
			
			if(classId!=0){
				solrQuery.addFilterQuery("classId:" + classId);
			}
			
			solrQuery.addFilterQuery("mallType:" + mallType);
			logger.info("pageSize = " + pageSize);
			logger.info("pageRows = " + (pageNow - 1) * pageSize);
			solrQuery.setStart((pageNow - 1) * pageSize);
			solrQuery.setRows(pageSize);
			
			// 如果查看的是学生店铺，则获取会员对应的供应商信息
			if (providerId != null) {
				logger.info("providerId = " + providerId);
				solrQuery.addFilterQuery("providerId:" + providerId);
			}
			if (brandId != null) {
				logger.info("brandId = " + brandId);
				solrQuery.addFilterQuery("brandId:" + brandId);
			}
			if (sortWord == null) {
				solrQuery.setSort("date", ORDER.desc);
			}else {
				ORDER orderMode = ORDER.asc;
				if (sortMode != null && sortMode == 1) {
					orderMode = ORDER.desc;
				}
				if (sortWord == 0) {
					solrQuery.setSort("date", orderMode);
				}else if (sortWord == 1) {
					solrQuery.setSort("sellNum", orderMode);
				}else if (sortWord == 2) {
					solrQuery.setSort("preferentialPrice", orderMode);
				}
			}
			String[] returnFields = {"normsValueId", "name", "goodsId", "photoUrl", "sellNum", "originalPrice", "preferentialPrice","points"};
			if (StringUtils.isNotEmpty(isStudent) && isStudent.equals("1")) {
				// 学生店铺商品
				logger.info("学生店铺");
				solrQuery.addFilterQuery("isStudent:1");
				returnFields = (String[]) ArrayUtils.add(returnFields, "providerName");
				returnFields = (String[]) ArrayUtils.add(returnFields, "providerPhotoUrl");
			}
			
			solrQuery.setFields(returnFields);
			if (StringUtils.isNotEmpty(goodsName)) {
				while (matcher.find()) {
					builder = new StringBuilder("pinyin:");
					builder.append(matcher.group());
					logger.info("fq = " + builder.toString());
					solrQuery.addFilterQuery(builder.toString());
				}
			}
			
			logger.info("query = " + solrQuery);
			QueryResponse queryResponse = solrServer.query(solrQuery);
			logger.info("response time = " + queryResponse.getQTime());
			
			List<SearchField> fields = queryResponse.getBeans(SearchField.class);
			
			Map<String, Object> tempMap = new HashMap<String, Object>();
			tempMap.put("goodsList", fields);
			tempMap.put("classId", classId);

			map.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			map.put(Constant.DATA, tempMap);
			
		} catch (SolrServerException | DaoException | UnsupportedEncodingException de) {
			logger.error(de);
			throw new ServiceException(de);
		}
		return map;
	}

	 /**
	 * @Package com.sayimo.school.mall.module.goods.service.impl
	 * @Author 龚益君
	 * @MethodName:getBrandListByClassId
	 * @Description:获取分类下的品牌列表
	 * @param classId
	 * @return
	 * @throws ServiceException
	 * @Date 2016年7月7日,下午1:58:24
	 */
	@Override
	public Map<String, Object> getBrandListByClassId(Integer classId) throws ServiceException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> dataMap = new HashMap<String, Object>();
		try {
			if(classId==null||classId.equals("")){
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_REQUEST_PARAM_ERROR);
				return resultMap;
			}
			List list = goodsClassInterfaceDao.getBrandListByClassId(classId);
			dataMap.put("brandList", list);
			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			resultMap.put(Constant.DATA, dataMap);
		} catch (DaoException de) {
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR);
			logger.error(de);
			throw new ServiceException(de);
		}
		return resultMap;
	}
	
	private String getClassIds(String _para){
		String[] classIdArr = _para.split(",");
		Set classIdsSet = new HashSet();
		classIdsSet.addAll(Arrays.asList(classIdArr));
		return StringUtils.join(classIdsSet.toArray(), ",");
	}

}
